using DG.Tweening;
using System;
using UnityEngine;
using UnityEngine.UI;

public class MoveNumberText : MonoBehaviour
{
    public int number;
    private RectTransform rect;
    public float time = 0.1f;
    public int PreTimes = 0;
    public Text text;
    public float HeightPercent = 0.5f;
    private void Awake()
    {
        text = GetComponent<Text>();
        rect = transform as RectTransform;
        tmp = rect.pivot;
    }

    private int index = 0;
    public bool IsUp;

    [ContextMenu("Test")]
    public void Run()
    {
        PreRound(PreTimes, delegate
        {
            Run(number);
        });
    }

    void PreRound(int round, Action Onfinish)
    {
        if (round <= 0)
        {
            Onfinish();
            return;
        }
        round--;
        Run(9, delegate { PreRound(round, Onfinish); });
    }


    public void Run(int num, Action Onfinish = null)
    {
        index = 0;

        DoRounds(num, Onfinish);
    }

    private void DoRounds(int num, Action Onfinish = null)
    {
        if (num > 0)
            DoOneRound(delegate
            {
                index++;
                text.text = index.ToString();
                if (index < num)
                {
                    DoRounds(num, Onfinish);
                }
                else
                {
                    if (Onfinish != null)
                        Onfinish();
                }
            });
        else
        {
            text.text = "0";
            if (Onfinish != null)
                Onfinish();
        }
    }

    private void DoOneRound(Action onfinish = null)
    {
        float first = 0.5f;
        float second = 3 * HeightPercent;
        float third = -3 * HeightPercent;

        Tween(first, IsUp ? third : second).OnComplete(delegate
             {
                 Tween(!IsUp ? third : second, first).OnComplete(delegate
                 {
                      if (onfinish != null)
                          onfinish();
                  });
             });
    }

    private DG.Tweening.Core.TweenerCore<float, float, DG.Tweening.Plugins.Options.FloatOptions> Tween(float from, float to)
    {
        return DOTween.To(() => from, (y) =>
        {
            SetPivot(y);
        }, to, time / 2);
    }
    public void ResetValue()
    {

    }

    private Vector2 tmp;

    private void SetPivot(float y)
    {
        tmp.y = y;
        rect.pivot = tmp;
    }
}